package com.juyu.miliao.api.dao.rabbit;

import com.juyu.miliao.api.dao.mysql.UserInfoDao;
import com.juyu.miliao.api.domain.User;
import com.juyu.miliao.api.handler.IntegralRewardsAndPunishmentsHandler;
import com.juyu.miliao.api.service.LineTimeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.Session;
import org.springframework.session.data.redis.RedisOperationsSessionRepository;
import org.springframework.stereotype.Repository;

import com.juyu.miliao.api.domain.UserSpend;
import com.juyu.miliao.common.exception.InternalServerErrorException;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Repository
public class RabbitDao {
	@Autowired
	private RabbitTemplate rabbitTemplate;
	@Autowired
	private FindByIndexNameSessionRepository<? extends Session> sessionRepository;
	@Autowired
	private RedisOperationsSessionRepository redisOperationsSessionRepository;
	@Resource
	private LineTimeService lineTimeService;
	@Resource
	private UserInfoDao userInfoDao;

	@Autowired
	private IntegralRewardsAndPunishmentsHandler integralRewardsAndPunishmentsHandler;

	public void userSpend(UserSpend userSpend) {
		boolean success = rabbitTemplate.invoke(t -> {
			t.convertAndSend("userSpendExchange", "", userSpend);
			t.waitForConfirmsOrDie(1000);
			return true;
		});
		if (!success)
			throw new InternalServerErrorException("rabbitmq 处理数据失败");
	}

//	public void updateUserInfo(User user){
//		User msg = new User();
//		msg.setUserId(user.getUserId());
//		rabbitTemplate.convertAndSend("updateUserInfoExchange", "", msg);
//	}

	/**
	 * 封禁帐号-mq消息
	 * @param userId
	 */
	@RabbitHandler
	@RabbitListener(queuesToDeclare = @Queue("suspendUserByIdExchange"))
	public void immediateProcess(String userId) {
		// 查询 PrincipalNameIndexName（Redis 用户信息的 key），结合自身业务逻辑来实现
		// 查询用户的 Session 信息，返回值 key 为 sessionId
		Map<String, ? extends Session> sessionIdToSession = sessionRepository
				.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, userId);
		// 移除用户的 session 信息
		List<String> sessionIds = new ArrayList<>(sessionIdToSession.keySet());
		for (String session : sessionIds) {
			redisOperationsSessionRepository.deleteById(session);
		}
		User user = userInfoDao.getUserInfoById(Long.parseLong(userId));
		lineTimeService.countLineTime("3",userId, Instant.now().toEpochMilli()+"",user);
		integralRewardsAndPunishmentsHandler.suspend(Long.parseLong(userId));
		log.info("删除seesion执行完毕 ：" + userId);
	}
	
}
